202511302354 如何使用 unixsocket 进行 http 请求
202511302354 如何使用 unixsocket 进行 http 请求
当 HTTP 请求需要通过本地 Unix Domain Socket 进行通信时,URL 的写法取决于你使用的工具或库。以下是几种常见场景:
1. 使用 curl
# 基本格式
curl --unix-socket /path/to/socket.sock http://localhost/api/endpoint
# 示例:Docker API
curl --unix-socket /var/run/docker.sock http://localhost/containers/json
2. 使用 Node.js
const http = require('http');
const options = {
socketPath: '/path/to/socket.sock',
path: '/api/endpoint',
method: 'GET'
};
const req = http.request(options, (res) => {
// 处理响应
});
3. 使用 Python requests
import requests
from requests.adapters import HTTPAdapter
from requests_unixsocket import UnixAdapter
session = requests.Session()
session.mount('http+unix://', UnixAdapter())
# URL 格式:http+unix://<encoded_socket_path>/<path>
response = session.get('http+unix://%2Fvar%2Frun%2Fdocker.sock/containers/json')
4. 使用 wget
wget --method=GET --unix-socket=/path/to/socket.sock http://localhost/api/endpoint
关键点:
- Socket 路径:需要指定完整的 socket 文件路径(如
/var/run/docker.sock) - Host 部分:通常写
localhost或任意值,因为实际通信不走网络 - 路径编码:某些库(如 Python requests)需要对 socket 路径进行 URL 编码
- 协议前缀:有些库使用特殊协议如
http+unix://来标识 Unix socket 通信